<?php

namespace App\Controller\LazyCommon;

use App\Base\BaseConfig;
use App\Base\BaseController;
use App\Model\LazyCommon\PlatConfigModel;
use App\Model\LazyCommon\UserModel;
use App\Model\LazyCommon\UserInviteModel;
use App\Model\LazyCommon\WechatCodeModel;
use App\Model\LazyCommon\WechatModel;
use App\Model\LazyCommon\WechatReplyModel;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

//define('TOKEN_WECHAT', 'lllovenn');

/**
 * @route("/wechat")
 */
class ApiController extends BaseController
{
    protected $baseurl = BaseConfig::__BASE_URL__;

    /**
     * @route("/api",name="WechatApi")
     */
    public function index(Request $request)
    {
        $this->log_out($request->request->all());
        if ($this->valid($request))
        {
            // 判读是不是只是验证
            $echostr = $request->get('echostr');
            if (!empty($echostr))
            {
                return $this->render('Common/Wechat/valid.html.twig', array('output' => $echostr));
            }
            else
            {
                return $this->responseMsg();
            }
        }
        else
        {
            return $this->render('Common/Wechat/valid.html.twig', array('output' => ""));
        }
    }

    //接入验证
    private function valid(Request $request)
    {
        $token = TOKEN_WECHAT;

        $signature = $request->get('signature');
        $timestamp = $request->get('timestamp');
        $nonce = $request->get('nonce');

        $tmp_arr = array($token, $timestamp, $nonce);
        sort($tmp_arr,SORT_STRING);
        $tmp_str = implode($tmp_arr);
        $tmp_str = sha1($tmp_str);

        return ($tmp_str == $signature);
    }

    private function responseMsg()
    {
        $post_str = file_get_contents('php://input');
        $this->log_out($post_str);
        if(!empty($post_str))
        {
            $post_obj = simplexml_load_string($post_str, 'SimpleXMLElement', LIBXML_NOCDATA);
            $getMsgType = $post_obj->MsgType;//MsgType
            $this->log_out($getMsgType);
            $MsgType='t_'.$getMsgType[0];
            return $this->$MsgType($post_obj);
        }
        else
        {
            return $this->render('Common/Wechat/valid.html.twig', array('output' => "ERROR!"));
        }
    }

    private function outxml($post_obj,$data){
        $to = $post_obj->FromUserName;//用户openid
        $from = $post_obj->ToUserName;//公众号id

        $data['to']=$to;
        $data['from']=$from;
        $data['time']=time();
        return $this->render('Common/Wechat/response.xml.twig',$data);
    }


    private function def_out($post_obj,$data){

        $to = $post_obj->FromUserName;//用户openid
        $from = $post_obj->ToUserName;//公众号id

        $data['to']=$to;
        $data['from']=$from;
        $data['time']=time();

        return $this->render('Common/Wechat/text.xml.twig',$data);
    }

    private function t_text($post_obj){
        $wechat_id=$post_obj->FromUserName;
        $this->log_out($post_obj);
        switch ($post_obj->Content) {
            case "opid":
                $wechat_id=$post_obj->FromUserName;
                $data=array(
                    'type' => "text",
                    'content' => "$wechat_id",
                );
                return $this->def_out($post_obj,$data);
            default:
//                $picurl = $this->baseurl."/pinggu.png";
//                $data=array(
//                    'title'=>'高考查询·分数评估',
//                    'picurl' =>$picurl,
//                    'url' => $this->baseurl.$this->generateUrl("chkOpenid")."?sn=".$wechat_id,
//                    'des'=>"欢迎免费查询高考信息。",
//                );
//                return $this->outxml($post_obj,$data);


                $wechat_id=$post_obj->FromUserName;
                $PlatConfigModel = new PlatConfigModel($this->getDoctrine());
//                $PC = $PlatConfigModel->get(1);
//                $html = $PC->getText();
//                $html = "
//";
                $message = $post_obj->Content;
                $WechatReplyModel = new WechatReplyModel($this->getDoctrine());
                $all = $WechatReplyModel->getRep()->findAll();
                $reply = "智能客服给您提示:\n";
                $reply = "智能客服:\n";
                $match = 0;
                foreach ($all as $item) {
                    $find = $item->getFind();
                    if (preg_match("/$find/i",$message)) {
                        $reply .= $item->getReply()."\n";
                        $match = 1;
                    }

                }
                $reply .= "\n\n常见问题汇总：<a href='http://shop.xuanyoung.com/wap/show/page?pid=1'>点此查看</a>";
                if ($match) {
                    $content = $reply;
                }else{
                    $content = BaseConfig::__WECHAT_AUTO_TEXT__;

                }

                $data=array(
                    'type' => "text",
                    'content' => $content,
                );
                return $this->def_out($post_obj,$data);
        }
    }

    private function t_event($post_obj){
        $wechat_id=$post_obj->FromUserName;

        $event = strtolower($post_obj->Event);
        switch ($event) {
            case "scan":
            case "view":
            case "click":
            case "subscribe":
            case "unsubscribe":

                break;
            default:

        }

        switch ($post_obj->EventKey) {
            case "CodeMain":
                $WechatCodeModel = new WechatCodeModel($this->getDoctrine());
                $WechatCode = $WechatCodeModel->getByOpenid($wechat_id);
                if ($WechatCode) {
                    //用户存在发送验证码
                    $num = rand(1000,9999);
                    $data=array(
                        'type' => "text",
                        'content' => $num,
                    );
                    $WechatCode->setCode($num)
                        ->setAddtime(time());
                    $this->myEm()->persist($WechatCode);
                    $this->myEm()->flush();

                    return $this->def_out($post_obj,$data);
                } else {
                    $data=array(
                        'title'=>'请绑定手机号',
                        'picurl' =>"",
                        'url' => $this->baseurl.$this->generateUrl("WechatBindPhone")."?id=".$wechat_id,
                        'des'=>"首次使用微信验证码需要绑定手机号，绑定后不可变更请谨慎操作",
                    );
                    //todo 验证码绑定需要设定单独的Entity
                    return $this->outxml($post_obj,$data);
                }
            default:
                $wechat_id=$post_obj->FromUserName;
                $data=array(
                    'type' => "text",
                    'content' => "我知道你会来，所以萱氧一直在等你！",
                );
                return $this->def_out($post_obj,$data);
        }
    }

    private function event_subscribe($post_obj)//关注和扫码关注
    {
        if ($post_obj->EventKey) {//带参数扫描
            $key = $post_obj->EventKey;
            //绑定关注事件
            $wechat_id=$post_obj->FromUserName;
            $UserModel = new UserModel($this->getDoctrine());
            $UserInviteModel = new UserInviteModel($this->getDoctrine());
            $user = $UserModel->getByWeChetId($wechat_id);

            $userInvite = $UserInviteModel->getUser($user->getId());
            if (!$userInvite) {
                //没有邀请记录说明没有绑定过
                //获取key ,获取上级信息
                $UserInviteModel->addUser($user->getId(),$key);
            }

        }else{

        }
    }
    private function event_scan($post_obj)//已关注的用户再扫码
    {
        if ($post_obj->EventKey) {//带参数扫描

        }
    }
    private function event_unsubscribe($post_obj)//取消关注
    {

    }
    private function event_click($post_obj)//点击事件，拉取消息
    {
        $key = $post_obj->EventKey;
    }
    private function event_view($post_obj)//点击事件，跳转链接
    {
        $key = $post_obj->EventKey;
        $key = strtolower($key);
        switch ($key) {
            case "index":
                break;
            case "user":
                break;
        }
    }

};